Dynamic data analysis with Shiny

David Granjon (cynkra GmbH)

I get a pretty cool local R program …

… But nobody can use it.

But wait … web applications exist for a long time.

  • Sure, you just need to convert R to web languages (HTML, CSS, JS).

Isn’t there an easier way for R developers?

Welcome Shiny?

  • Make web development accessible to R people.
  • Unleash programs interactivity.
  • Point and click data Science.

How does a Shiny app looks?

Is the code complex?

Anatomy of a Shiny app

UI: shiny is able to produce HTML from R!

shiny::selectInput("select", "Select", colnames(mtcars))


<div class="form-group shiny-input-container">
  <label class="control-label" id="select-label" for="select">Select</label>
  <div>
    <select id="select" class="shiny-input-select"><option value="mpg" selected>mpg</option>
<option value="cyl">cyl</option>
<option value="disp">disp</option>
<option value="hp">hp</option>
<option value="drat">drat</option>
<option value="wt">wt</option>
<option value="qsec">qsec</option>
<option value="vs">vs</option>
<option value="am">am</option>
<option value="gear">gear</option>
<option value="carb">carb</option></select>
    <script type="application/json" data-for="select" data-nonempty="">{"plugins":["selectize-plugin-a11y"]}</script>
  </div>
</div>

You don’t need to write any HTML, CSS and JS (but you could 😈…)

Initialize interactivity with inputs

  • UI: create elements with an unique inputId, variable.
  • Server: recover its value within input[["variable"]] or input$variable.
  • input is read only.

Render output elements

  • Use a suitable renderer: renderTable, renderPlot, …
  • Assign unique outputId: data.
  • Recover output on the UI (IDs must match!): tableOutput, plotOutput, …
  • output is readonly.

Intermediate results with reactive expressions

  • Return values.
  • Take dependencies on anything reactive inside (input, other reactives).
  • No side effects! (write.csv, …).
  • Lazy: don’t run if not used.
  • cached: only recompute when needed.

Overview of the reactive graph

Reactive graph example

Your turn

Adjustement of logistic model (Verhulst)

We consider the logistic model used to describe population growth.

\[ \frac{dN}{dt} = rN \left( 1 - \frac{N}{K} \right) \] whose solution is given by:

\[ N(t) = \frac{K}{1 + \left(\frac{K - N_0}{N_0}\right) e^{-rt}} \] Where:

  • N(t) is the population size at time t.
  • K is the carrying capacity.
  • r is the intrinsic growth rate.
  • \(N_0\) is the initial population size at time t=0.

Complete Exercise 1

We define the following objective function, \(y_i\) being the observed data and \(f(x_i, \beta)\) the model predictions given a set of parameters \(\beta\):

\[ S(\beta) = \sum_{i=1}^{n} (y_i - f(x_i, \beta))^2 \] We want to minimize this ( represents the best parameters estimate):

\[ \hat{\beta} = \arg \min_{\beta} S(\beta) =\arg \min_{\beta} \sum_{i=1}^{n} (y_i - f(x_i, \beta))^2 \]